package com.geeyuu.android.activity;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

import com.geeyuu.android.R;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.ImageLoder;
import com.geeyuu.android.utils.LogUtil;

public class FriendProfileAvtivity extends BaseActivity {
    
    private long uid;
    private BaseUserInfo baseUserInfo;
    private ImageLoder mImageLoder;
    private MyHandler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "FriendProfileAvtivity_" + CommonUtil.getRandomStr();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_profile_layout);
        
        uid = getIntent().getLongExtra("userId", 0);
        if(uid == 0){
            LogUtil.e(TAG, "周边用户activity传过来的uid不合法");
            finish();
            return;
        }
        
        mHandler = new MyHandler(this);
        baseUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
        mImageLoder = new ImageLoder(getApplicationContext());
        
        initTitleViews();
        initContentViews();
        
        startBindService();
        
    }
    
    private static class MyHandler extends Handler{
        private final WeakReference<FriendProfileAvtivity> friendProfileAvtivity;
        public MyHandler(Context context){
            friendProfileAvtivity = new WeakReference<FriendProfileAvtivity>((FriendProfileAvtivity)context);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                friendProfileAvtivity.get().initUserBaseInfoView();
                friendProfileAvtivity.get().initHideUserBaseInfo();
                break;
            case 1:
                friendProfileAvtivity.get().initPublicPhotoViews();
                break;
            case 2:
                friendProfileAvtivity.get().initPrivatePhotoViews();
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        stopBindService();
        if(null != mImageLoder){
            mImageLoder.destory();
        }
        super.onDestroy();
    }
    
    private ProgressBar pubProgress;
    private ProgressBar priProgress;
    private ProgressBar baseInfoProgress;

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        
        switch (cmd) {
        case ProtocolCommand.CMD_QUERY_USER_INFO: 
            if(isMsgNormal){
                BaseUserInfo nowUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
                if(nowUserInfo.lastAlbumModifyTime != baseUserInfo.lastAlbumModifyTime){
                    Bundle bundle2 = new Bundle();
                    bundle2.putString(DataKey.S_KEY_USER_PHOTO_QUERY_UID, String.valueOf(uid));
                    bundle2.putString(DataKey.S_KEY_USER_PHOTO_QUERY_PAGE_INDEX, "0");
                    bundle2.putString(DataKey.S_KEY_USER_PHOTO_QUERY_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC);
                    sendMsgToService(ProtocolCommand.CMD_QUERY_ALBUM, bundle2);
                    
                    if(pubProgress == null){
                        pubProgress = (ProgressBar)findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.VISIBLE);
                    
                }
                baseUserInfo = nowUserInfo;
                mHandler.sendEmptyMessage(0);
            }else{
                AndroidUtil.showToast(getApplicationContext(), "读取网络数据失败");
            }
            if(baseInfoProgress == null){
                baseInfoProgress = (ProgressBar)findViewById(R.id.load_baseinfo_progress);
            }
            baseInfoProgress.setVisibility(View.GONE);
            break;
        case ProtocolCommand.CMD_QUERY_ALBUM:
            int photoType = bundle.getInt("photoType");
            if(isMsgNormal){
                baseUserInfo = BaseUserInfo.getUserInfo(getApplicationContext(), uid);
                if(photoType == 1){ //pub
                    
                    if(pubProgress == null){
                        pubProgress = (ProgressBar)findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.GONE);
                    
                    if(priProgress == null){
                        priProgress = (ProgressBar)findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.VISIBLE);
                    
                    LogUtil.d(TAG, "更新公开相册");
                    mHandler.sendEmptyMessage(1);
                    Bundle bundle3 = new Bundle();
                    bundle3.putString(DataKey.S_KEY_USER_PHOTO_QUERY_UID, String.valueOf(uid));
                    bundle3.putString(DataKey.S_KEY_USER_PHOTO_QUERY_PAGE_INDEX, "0");
                    bundle3.putString(DataKey.S_KEY_USER_PHOTO_QUERY_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PRIVATE);
                    sendMsgToService(ProtocolCommand.CMD_QUERY_ALBUM, bundle3);
                }else if(photoType == 2){ //pri
                    
                    if(priProgress == null){
                        priProgress = (ProgressBar)findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.GONE);
                    
                    LogUtil.d(TAG, "更新私密相册");
                    mHandler.sendEmptyMessage(2);
                }
            }else{
                if(photoType == 1){
                    if(pubProgress == null){
                        pubProgress = (ProgressBar)findViewById(R.id.load_pub_progress);
                    }
                    pubProgress.setVisibility(View.GONE);
                }else if(photoType == 2){
                    if(priProgress == null){
                        priProgress = (ProgressBar)findViewById(R.id.load_pri_progress);
                    }
                    priProgress.setVisibility(View.GONE);
                }
                AndroidUtil.showToast(getApplicationContext(), "读取网络数据失败");
            }
            break;
        }
        
    }

    @Override
    protected void onConnectServiceCallBack() {
        Bundle bundle = new Bundle();
        bundle.putString(DataKey.S_KEY_QUERY_USER_INFO_UID, String.valueOf(uid));
        sendMsgToService(ProtocolCommand.CMD_QUERY_USER_INFO, bundle);
    }

    private void initTitleViews() {
        Button topLeftButton = (Button)findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.title_back_icon, 0, R.drawable.friend_profile_title_icon, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 5), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if(null == vl){
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        }else{
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        topLeftButton.setOnClickListener(mOnClickListener);
    }

    private void initContentViews() {
        TextView lookFriendProfileButton = (TextView)findViewById(R.id.to_profile_or_to_chat_button);
        lookFriendProfileButton.setText("对话");
        lookFriendProfileButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.go_chat_icon, 0, 0);
        lookFriendProfileButton.setOnClickListener(mOnClickListener);
        
        viewStub = (ViewStub)findViewById(R.id.more_info_container);
        clickTips = (TextView)findViewById(R.id.show_more_info_button);
        clickTips.setOnClickListener(mOnClickListener);
        clickTips2 = (TextView)findViewById(R.id.show_more_info_button2);
        clickTips2.setOnClickListener(mOnClickListener);
        
        View bottomViews = findViewById(R.id.bottom_views_container);
        bottomViews.findViewById(R.id.exchanged_private_photo).setOnClickListener(mOnClickListener);
        
        View payAttention = bottomViews.findViewById(R.id.pay_attention);
        payAttention.setVisibility(View.VISIBLE);
        payAttention.setOnClickListener(mOnClickListener);
        
        View reportHime = bottomViews.findViewById(R.id.report_him);
        reportHime.setVisibility(View.VISIBLE);
        reportHime.setOnClickListener(mOnClickListener);
        
        initUserBaseInfoView();
        initPublicPhotoViews();
        initPrivatePhotoViews();
        
    }
    
    private void initUserBaseInfoView(){
        ImageView avatarImageView = (ImageView)findViewById(R.id.friend_profile_avatar);
        mImageLoder.add(baseUserInfo.mainPhotoID, avatarImageView, true);
        
        TextView popValue = (TextView)findViewById(R.id.pop_value);
        popValue.setText("X " + baseUserInfo.popValue);
        
        TextView isOnlineAndDistance = (TextView)findViewById(R.id.is_online_and_distance);
        String isOrNotOnline = baseUserInfo.isOnline == BaseUserInfo.USER_ONLINE ? "在线" : "不在线";
        String distance = baseUserInfo.distance + " km";
        isOnlineAndDistance.setText(isOrNotOnline + "          " + distance);
        
        TextView userNickName = (TextView)findViewById(R.id.user_nick_name);
        userNickName.setText(baseUserInfo.nickName);
        
        TextView userRole = (TextView)findViewById(R.id.user_role);
        userRole.setText(baseUserInfo.getRealRole());
    }
    
    private void initHideUserBaseInfo(){
        if(userBaseInfoView != null){
            TextView age = (TextView)userBaseInfoView.findViewById(R.id.profile_age_textview);
            age.setText(baseUserInfo.age + "");
            
            TextView height = (TextView)userBaseInfoView.findViewById(R.id.profile_height_textview);
            height.setText(baseUserInfo.height + " cm");
            
            TextView weight = (TextView)userBaseInfoView.findViewById(R.id.profile_weight_textview);
            weight.setText(baseUserInfo.weight + " kg");
            
            TextView sign = (TextView)userBaseInfoView.findViewById(R.id.profile_sign_textview);
            sign.setText(baseUserInfo.sign);
        }
    }
    
    private OnClickListener photoClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int index = (Integer)v.getTag();
            int type = (Integer)v.getTag(R.string.photo_key);
            Intent intent = new Intent(FriendProfileAvtivity.this, PhotoBrowserActivity.class);
            intent.putExtra("index", index);
            intent.putExtra("type", type);
            intent.putExtra("uid", uid);
            if(null != publicPhotoIdsArray){
                intent.putExtra("publicPhotoIds", publicPhotoIdsArray);
            }
            if(BaseUserInfo.isUserInMyShareList(getApplicationContext(), uid) && null != privatePhotoIdsArray){
                intent.putExtra("privatePhotoIds", privatePhotoIdsArray);
            }
            startActivity(intent);
        }
    };
    
    private TextView publicCount;
    private LinearLayout publicPhotoContainer;
    private String[] publicPhotoIdsArray;
    
    private TextView privateCount;
    private LinearLayout privatePhotoContainer;
    private String[] privatePhotoIdsArray;
    
    private void initPublicPhotoViews(){
        final int dip5 = AndroidUtil.dip2px(getApplicationContext(), 5);
        final int width = ((mImageLoder.screenWidth - AndroidUtil.dip2px(getApplicationContext(), 25))/7)*2 + dip5;
        String publicPhotoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(), uid, BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS);
        if(!CommonUtil.isEmpty(publicPhotoIds)){
            publicPhotoIdsArray = publicPhotoIds.split(",");
            if(publicPhotoIdsArray != null && publicPhotoIdsArray.length > 0){
                if(null == publicCount){
                    publicCount = (TextView)findViewById(R.id.public_photo_title);
                }
                publicCount.setText("公开相册("+publicPhotoIdsArray.length+"/10)");
                if(null == publicPhotoContainer){
                    publicPhotoContainer = (LinearLayout)findViewById(R.id.friend_public_photo_container);
                }
                publicPhotoContainer.removeAllViews();
                int indexTag = 0;
                for(String photoId : publicPhotoIdsArray){
                    ImageView imageView = new ImageView(this);
                    imageView.setScaleType(ScaleType.FIT_XY);
                    imageView.setOnClickListener(photoClick);
                    imageView.setTag(indexTag);
                    imageView.setTag(R.string.photo_key, 0);
                    imageView.setPadding(dip5, 0, 0, 0);
                    ViewGroup.LayoutParams vl = new ViewGroup.LayoutParams(width, width);
                    imageView.setLayoutParams(vl);
                    publicPhotoContainer.addView(imageView);
                    mImageLoder.add(photoId, imageView, true);
                    indexTag++;
                }
            }
        }
    }
    
    private void initPrivatePhotoViews(){
        final int dip5 = AndroidUtil.dip2px(getApplicationContext(), 5);
        final int width = ((mImageLoder.screenWidth - AndroidUtil.dip2px(getApplicationContext(), 25))/7)*2 + dip5;
        String privatePhotoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(), uid, BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS);
        if(!CommonUtil.isEmpty(privatePhotoIds)){
            privatePhotoIdsArray = privatePhotoIds.split(",");
            if(privatePhotoIdsArray != null && privatePhotoIdsArray.length > 0){
                if(privateCount == null){
                    privateCount = (TextView)findViewById(R.id.private_photo_title);
                }
                privateCount.setText("私密相册("+privatePhotoIdsArray.length+"/10)");
                if(privatePhotoContainer == null){
                    privatePhotoContainer = (LinearLayout)findViewById(R.id.friend_private_photo_container);
                }
                privatePhotoContainer.removeAllViews();
                int indexTag = 0;
                for(String photoId : privatePhotoIdsArray){
                    ImageView imageView = new ImageView(this);
                    imageView.setScaleType(ScaleType.FIT_XY);
                    imageView.setTag(indexTag);
                    imageView.setTag(R.string.photo_key, 1);
                    imageView.setPadding(dip5, 0, 0, 0);
                    ViewGroup.LayoutParams vl = new ViewGroup.LayoutParams(width, width);
                    imageView.setLayoutParams(vl);
                    privatePhotoContainer.addView(imageView);
                    if(BaseUserInfo.isUserInMyShareList(getApplicationContext(), uid)){
                        mImageLoder.add(photoId, imageView, true);
                        imageView.setOnClickListener(photoClick);
                    }else{
                        imageView.setImageResource(R.drawable.default_avatar);
                    }
                    indexTag++;
                }
            }
        }
    }
    
    private ViewStub viewStub;
    private View userBaseInfoView;
    private TextView clickTips;
    private TextView clickTips2;
    private boolean isMoreBaseInfoShowing = false;
    
    private void setHideViews(){
        isMoreBaseInfoShowing = !isMoreBaseInfoShowing;
        if(isMoreBaseInfoShowing){
            if(viewStub != null && userBaseInfoView == null){
                userBaseInfoView = viewStub.inflate();
                initHideUserBaseInfo();
            }else{
                userBaseInfoView.setVisibility(View.VISIBLE);
            }
            clickTips.setBackgroundResource(R.drawable.click_up);
            clickTips2.setText("点击收起");
        }else{
            if(null != userBaseInfoView){
                userBaseInfoView.setVisibility(View.GONE);
            }
            clickTips.setBackgroundResource(R.drawable.click_down);
            clickTips2.setText("点击展开");
        }
    }
    
    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.exchanged_private_photo:
                
                break;
                
            case R.id.to_profile_or_to_chat_button:
                startActivity(new Intent(FriendProfileAvtivity.this, ChatActivity.class).putExtra("uid", uid));
                overridePendingTransition(R.anim.in, R.anim.out);
                break;
                
            case R.id.top_left_button:
                finish();
                if(!Activity0.isFromActivity0){
                    overridePendingTransition(R.anim.in, R.anim.out);
                }
                break;
                
            case R.id.show_more_info_button:
                setHideViews();
                break;
                
            case R.id.show_more_info_button2:
                setHideViews();
                break;
                
            }
        }
    };
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(!Activity0.isFromActivity0){
            overridePendingTransition(R.anim.in, R.anim.out);
        }
    }
    
}
